from Controller.BaseController import BaseController
from Utility import FormData
from Utility import ViewName
from Utility import TemplateValueName
from Common.CompanyOrg import Company
from Common.ComAdmin import ComAdmin
from Common.DuplicatedInstanceError import DuplicatedInstanceError
from urllib import quote 


class CreateCompanyController(BaseController):
    """
    eventually, this page is public to everyone
    """
    def get(self):
        self.Render(ViewName.D_CREATECOMPANY, None)
        
    
    def post(self):
        companyName = self.request.get(FormData.COMPANY_NAME)       
        userName = self.request.get(FormData.USER_NAME)
        email = self.request.get(FormData.EMAIL)
        password = self.request.get(FormData.PASSWORD)
        
        # TODO: User input verification
        
        # create company
        try:
            c = Company(key_name=companyName,
                        CompanyName=companyName)
            c.TransactionPut()
        except DuplicatedInstanceError:
            message="<div class='warn'> Company ["+companyName + "] already exists!"+"</div>"
            template_values = {"Message": message, "UserName":userName, "CompanyName":companyName, "Email":email}
            self.Render(ViewName.D_CREATECOMPANY, template_values)
            return
        
        # create sysadmin
        try:
            u = ComAdmin(parent = c,
                     key_name=userName,
                     UserName=userName, 
                     Password=password, 
                     DisplayName=userName,
                     Email=email,
                     Ref_Company = c)
            u.TransactionPut()
        except DuplicatedInstanceError:
            message="<div class='warn'>User ["+userName + "] already exists!"+"</div>"
            template_values = {"Message": message, "UserName":userName, "CompanyName":companyName, "Email":email}
            self.Render(ViewName.D_CREATECOMPANY, template_values)
            return
        
        self.DeleteCurrentSession()
        
        # the format method is not support in live environment
        #URL = DEFAULT_CREATECOMPANY_REDIRECT.format(quote(companyName), quote(r"/c/g"))
        URL = '/login?org=' + quote(companyName) + '&re=' + quote(r"/c/g")
        template_values = { TemplateValueName.REDIRECT_URL:URL, "CompanyName":companyName, "UserName":userName }
        self.Render(ViewName.D_CREATECOMPANY_RESPONSE,template_values)
    